﻿#region Librerias

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ESF.Web.Pages;
using ESF.SSO.Core.Entities;
using ESF.SSO.Presenter.Admin.User;
using ESF.Web.ServerControls;
using ESF.General;
using ESF.Web;
using System.Globalization;
using ESF.SSO.Core.Entities.BasicReferences;
using ESF.SSO.Core.BusinessLogic;
using ESF.General.Entity;
using ESF.SSO.Web.Tools.Modules;

#endregion


public partial class User_ResponseContactUs : BaseCustomBrowsePagedPage<ContactUs, BrowseContactUsPresenter, IBrowseContactUsViewer>, IBrowseContactUsViewer
{
	#region Propiedades

	public string CountResumen 
	{
		set
		{
			lblCountResumen.Text = value;
		}
	} 


	public List<BasicReference> ExtraAppSteps
	{
		get
		{
			return ViewState["ExtraAppSteps"] as List<BasicReference>;
		}
		set
		{
			ViewState["ExtraAppSteps"] = value;
		}
	}


	public string filExtraValue
	{
		set
		{
			JS.AddEndJS (Page, "ClearExtraValue ();");
			hidExtraValue.Value = string.Empty;
		}
		get
		{
			return hidExtraValue.Value;
		}
	}

	#endregion
	
	
	#region Carga Inicial
	
	protected void Page_Load(object sender, EventArgs e)
    {
		_Presenter = new BrowseContactUsPresenter (this);

		if (!IsPostBack)
		{
			lblTitle.Text = Title;

			_Presenter.Load();

			#region Extra Pasos

			ifrStep_3.Visible = false;

			if (!DataHelper.IsEmpty(ExtraAppSteps))
			{
				ifrStep_3.Visible = true;

				btnBrowse.OnClientClick = "SetExtraValue ();";

				JS.AddEndJS(Page, "function ClearExtraValue () { var ifr = document.getElementById ('" + ifrStep_3.ClientID + "'); ifr.contentWindow.SetValue (''); }");
				
				JS.AddEndJS(Page, "function SetExtraValue () { var ifr = document.getElementById ('" + ifrStep_3.ClientID + "'); $('#" + hidExtraValue.ClientID + "').val (ifr.contentWindow.GetValue ()); }");

				JS.AddEndJS(Page, "ifrStep_3_IsValid = function (source, args) { var ifr = document.getElementById ('" + ifrStep_3.ClientID + "'); args.IsValid = ifr.contentWindow.IsValid (); }");

				cvlIframeOtherApps.ClientValidationFunction = "ifrStep_3_IsValid";

				// TODO: soportar mas de una aplicacion
				foreach (BasicReference app in ExtraAppSteps)
				{
					ifrStep_3.Attributes["src"] = RequestHelper.AppendVarValueToHTTPURL(app.Extra_I + "/" + app.Extra_II, PageHelper.KEY_SETDOCUMENTDOMAIN, AuthenticationModule.TicketDomain);
				}
			}
			else
			{
				cvlIframeOtherApps.Enabled = false;
			}

			#endregion

			ListLoader.LoadList (ddlContactUsType, WebGeneral.ListBasicReference (BasicReferenceTypes.ContactUsType));

			ListLoader.LoadYESNOList (ddlWithResponse);

			_Presenter.Browse ();
		}
    }

	#endregion


	#region Funciones Sobreescritas

	protected override DataPagging GetDataPagging()
	{
		return dpggrvResults;
	}


	protected override GridView GetGridView()
	{
		return grvResults;
	}


	public override IEnumerable<ContactUs> GetSelectedItems(IEnumerable<string> pIDs)
	{
		foreach (string id in pIDs)
		{
			yield return new ContactUs () { ID = id };
		}
	}

	#endregion


	#region Eventos de la Grilla
	
	protected void grvResults_RowDataBound(object sender, GridViewRowEventArgs e)
	{
		ContactUs item;

		User senderUser = null;
		User replyUser = null;


		if (e.Row.RowType == DataControlRowType.DataRow)
		{
			item = e.Row.DataItem as ContactUs;

			GridLoader.SetValueIDForRow (e.Row, item.ID);

			(e.Row.FindControl("lblRowIndex") as Label).Text = item.calRowIndex.ToString();

			if (!string.IsNullOrEmpty (item.filUserAlias))
			{
				senderUser = CtrlUser.Get (new User () { Alias = item.filUserAlias });
			}

			if (!string.IsNullOrEmpty (item.ResponseUserAlias))
			{
				replyUser = CtrlUser.Get (new User () { Alias = item.ResponseUserAlias });
			}

			if (senderUser != null)
			{
				(e.Row.FindControl ("lblUserAlias") as Label).Text = TextHelper.FormatIfValueNotEmpty ("<b>Usuario:</b> {0}<br/>", senderUser.Alias);
				(e.Row.FindControl ("lblCalUserFullName") as Label).Text = TextHelper.FormatIfValueNotEmpty ("<b>Nombre:</b> {0}<br/>", senderUser.calFullName);
				
				if (!DataHelper.IsEmpty (senderUser.Locations))
				{
					(e.Row.FindControl ("lblHomePhone") as Label).Text = senderUser.Locations.First ().PhoneNumber;
				}
				
				if (senderUser.Enterprise != null)
				{
					(e.Row.FindControl ("lblEnterprise") as Label).Text = senderUser.Enterprise.Name;
				}
			}

			if (replyUser != null)
			{
				(e.Row.FindControl ("lblResponseUserAlias") as Label).Text = TextHelper.FormatIfValueNotEmpty ("<b>Tramitado por:</b> {0}<br/>", replyUser.Alias);
				(e.Row.FindControl ("lblResponseCalUserFullName") as Label).Text = TextHelper.FormatIfValueNotEmpty ("<b>Nombre:</b> {0}<br/>", replyUser.calFullName);
			}

			(e.Row.FindControl ("lblSenderEmail") as Label).Text = item.SenderEmail;
			(e.Row.FindControl ("lblCreationDateTime") as Label).Text = item.CreationDateTime.Value.ToString ("yyyy-MM-dd h:mm:ss tt");
			(e.Row.FindControl ("lblTitle") as Label).Text = TextHelper.FormatIfValueNotEmpty ("<b>Asunto:</b> {0}<br/>", item.Title);
			(e.Row.FindControl ("hidTitle") as HiddenField).Value = item.Title;

			(e.Row.FindControl ("lblContactUsType") as Label).Text = TextHelper.FormatIfValueNotEmpty ("<b>Categoria:</b> {0}<br/>", item.ContactUsTypeID.Name);

			(e.Row.FindControl ("lblResponseDateTime") as Label).Text = TextHelper.FormatIfValueNotEmpty ("<b>Fecha y Hora:</b> {0:yyyy-MM-dd h:mm:ss tt}<br/>", item.ResponseDateTime);
			
			(e.Row.FindControl ("rfvtxtResponse") as RequiredFieldValidator).ValidationGroup = string.Format ("valResponse_{0}", e.Row.RowIndex);

			if (!TextHelper.IsEmpty (item.Response))
			{
				e.Row.FindControl ("btnSendResponse").Visible = false;
				(e.Row.FindControl ("txtResponse") as TextBox).Text = item.Response;
				(e.Row.FindControl ("txtResponse") as TextBox).ReadOnly = true;
			}
			else
			{
				(e.Row.FindControl ("btnSendResponse") as Button).ValidationGroup = string.Format ("valResponse_{0}", e.Row.RowIndex);
			}

			(e.Row.FindControl ("txtComments") as TextBox).Text = item.Comments;
		}
	}


	protected void grvResults_RowCommand(object sender, GridViewCommandEventArgs e)
	{
		grvResults.SelectedIndex = GridLoader.GetGridViewRowIndex (e.CommandSource);

		if (e.CommandName == "SendResponse")
		{
			_Presenter.SendResponse ();
		}
	}

	#endregion


	#region Campos del Interface

	public bool? filWithResponse
	{
		get
		{
			return TextHelper.GetNullableBool (ddlWithResponse.SelectedValue);
		}
		set
		{
			ListLoader.Select (ddlWithResponse, value);
		}
	}


	public int? filContactUsTypeID 
	{
		set { ListLoader.Select (ddlContactUsType, value); }
		get { return TextHelper.GetNullableInt (ddlContactUsType.SelectedValue); }
	}

	public string filUserFullName
	{
		get
		{
			return txtUserFullName.Text;
		}
		set
		{
			txtUserFullName.Text = value;
		}
	}


	public int? filUserIdentificationTypeID { set { ListLoader.Select (ddlUserIdentificationType, value); } get { return TextHelper.GetNullableInt (ddlUserIdentificationType.SelectedValue); } }

	
	public string filUserIdentificationNumber { set { txtUserIdentificationNumber.Text = value; } get { return txtUserIdentificationNumber.Text; } }


	public string filSenderEmail
	{
		get
		{
			return txtSenderEmail.Text;
		}
		set
		{
			txtSenderEmail.Text = value;
		}
	}


	public DateTime? filMessageStartDate
	{
		get
		{
			return TextHelper.GetNullableDate (txtStartMessageDate.Text);
		}
		set
		{
			if (value == null)
			{
				txtStartMessageDate.Text = string.Empty;
			}
		}
	}

	public DateTime? filMessageEndDate
	{
		get
		{
			return TextHelper.GetNullableDate (txtEndMessageDate.Text);
		}
		set
		{
			if (value == null)
			{
				txtEndMessageDate.Text = string.Empty;
			}
		}
	}


	public string SelectedID
	{
		get { return GridLoader.GetValueIDStringForRow (grvResults.SelectedRow); }
	}

	public string SelectedSenderEmail
	{
		get { return (grvResults.SelectedRow.FindControl ("lblSenderEmail") as Label).Text; }
	}

	public string SelectedResponse
	{
		get { return (grvResults.SelectedRow.FindControl ("txtResponse") as TextBox).Text; }
	}

	public DateTime SelectedCreationDateTime 
	{ 
		get 
		{ 
			return DateTime.ParseExact (
				(grvResults.SelectedRow.FindControl ("lblCreationDateTime") as Label).Text.Replace ("a.m.", string.Empty).Replace ("p.m.", string.Empty).Trim (), 
				"yyyy-MM-dd h:mm:ss", 
				CultureInfo.InvariantCulture); 
		} 
	}

	public string SelectedTitle { get { return (grvResults.SelectedRow.FindControl ("hidTitle") as HiddenField).Value; } }

	#endregion	
}